package com.base.cn.platform.os.controller.course.open;

import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.TT.TTServiceUtils;
import com.base.cn.platform.os.common.utils.course.CourseOpenForm;
import com.base.cn.platform.os.common.utils.course.MaterialType;
import com.base.cn.platform.os.common.utils.http.HttpUtil;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.user.LoginForm;
import com.base.cn.platform.os.entity.course.count.CourseOpenSumCount;
import com.base.cn.platform.os.entity.course.open.CourseOpen;
import com.base.cn.platform.os.entity.course.open.CourseOpenBespeak;
import com.base.cn.platform.os.entity.course.open.CourseOpenCondition;
import com.base.cn.platform.os.service.course.cloud.CloudServiceBiz;
import com.base.cn.platform.os.service.course.open.CourseOpenBespeakBiz;
import com.base.cn.platform.os.service.course.open.CourseOpenBiz;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.op.coupon.OpCouponCodeService;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import com.github.pagehelper.PageInfo;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

/**
 * 免费直播课程Controller接口
 *
 * @author s.li
 * @create 2018-05-03-16:17
 */
@RestController
@RequestMapping("/course")
public class CourseOpenController extends BaseController {
    @Autowired
    private CourseOpenBiz courseOpenBiz;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private CloudServiceBiz cloudServiceBiz;
    @Autowired
    private OpCouponCodeService opCouponCodeService;
    @Autowired
    private TTServiceUtils ttServiceUtils;

    /**
     * 查询多条件免费直播数量
     * @param condition 查询条件对象
     * @return 返回数量
     */
    @RequestMapping("/getCourseOpenCount")
    public BigDecimal getCourseOpenCount(@RequestBody CourseOpenCondition condition){
        return courseOpenBiz.getCourseOpenCount(condition);
    }

    /**
     * 保存免费直播课程
     * @param courseOpen 免费直播课程对象
     * @return CourseOpen
     */
    @RequestMapping("/saveCourseOpen")
    public Map<String,Object> saveCourseOpen(@RequestBody CourseOpen courseOpen){
        if (StringUtils.isEmpty(courseOpen.getCourseName())) {
            return ResultUtil.ERROR("请输入免费直播管理名称");
        }
        if (courseOpen.getCourseName().trim().length() > 30) {
            return ResultUtil.ERROR("免费直播名称不能超过30个字符");
        }
        String message = StringUtils.checkSubjectCondition(courseOpen.getSubjectIds());
        if(message !=null){
            return ResultUtil.ERROR(message);
        }
        if (courseOpen.getPlayType().equals("CC")) {
            if (!DataUtil.idIsNotNull(courseOpen.getTeacherId())) {
                return ResultUtil.ERROR("请选择授课讲师");
            }
            if (StringUtils.isEmpty(courseOpen.getLiveUrl())) {
                return ResultUtil.ERROR("请填写直播间识别码");
            }
            if (StringUtils.isEmpty(courseOpen.getRoomId())) {
                return ResultUtil.ERROR("请添加直播间ID");
            }
            if (StringUtils.isEmpty(courseOpen.getTeacherCode())) {
                return ResultUtil.ERROR("请添加直播间讲师参加码");
            }
            courseOpen.setTeacherCode(courseOpen.getTeacherCode().trim());
            if (StringUtils.isEmpty(courseOpen.getStudentCode())) {
                return ResultUtil.ERROR("请添加直播间学生参加码");
            }
            courseOpen.setStudentCode(courseOpen.getStudentCode().trim());
            if (StringUtils.isEmpty(courseOpen.getAdminCode())) {
                return ResultUtil.ERROR("请添加直播间助教参加码");
            }
        }else{
            if (StringUtils.isEmpty(courseOpen.getId())){ //新建直播间
                Map resultMap = ttServiceUtils.create3TLiveData(courseOpen.getLiveName(),courseOpen.getLiveNotice(),courseOpen.getOpenTime(),courseOpen.getEndTime(),courseOpen.getLiveType(),courseOpen.getTeacherId(),courseOpen.getTutorOne());
                if((boolean) resultMap.get("success")){
                    Map entity = (Map) resultMap.get("entity");
                    courseOpen.setRoomId(entity.get("classId").toString());
                }else{
                    return resultMap;
                }
            }
        }
        if (ObjectUtils.isEmpty(courseOpen.getOpenTime())) {
            return ResultUtil.ERROR("请指定免费直播开始时间");
        }
        if (ObjectUtils.isEmpty(courseOpen.getEndTime())) {
            return ResultUtil.ERROR("请指定免费直播结束时间");
        }
        if (StringUtils.isEmpty(courseOpen.getImageJson())) {
            return ResultUtil.ERROR("请选择免费直播管理封面");
        }
        if (!courseOpen.getOpenTime().before(courseOpen.getEndTime())) {
            return ResultUtil.ERROR("免费直播开始时间不能等于或大于结束时间");
        }

        courseOpen = courseOpenBiz.saveCourseOpen(courseOpen);
        return ResultUtil.SUCCESS("免费直播基本信息保存成功",courseOpen);
    }

    /**
     * 保存免费直播描述信息
     * @param courseOpen 免费直播数据对
     * @return CourseOpen
     */
    @RequestMapping("/saveCourseOpenInfo")
    public Map<String,Object> saveCourseOpenInfo(@RequestBody CourseOpen courseOpen){
        if(StringUtils.isNotEmpty(courseOpen.getTrait())){
            if(courseOpen.getTrait().trim().length()>255){
                return ResultUtil.ERROR("免费直播特点内容限制在255个文字以内");
            }
        }
        if(StringUtils.isNotEmpty(courseOpen.getSuitableUser())){
            if(courseOpen.getSuitableUser().trim().length()>255){
                return ResultUtil.ERROR("适宜学员内容限制在255个文字以内");
            }
        }
        courseOpen = courseOpenBiz.saveCourseOpenInfo(courseOpen);
        return ResultUtil.SUCCESS("免费直播描述保存成功",courseOpen);
    }

    /**
     * 修改免费直播状态
     * @param ids 免费直播ID
     * @param status 1：正常 2：冻结 3：删除
     */
    @RequestMapping("/updateCourseOpenStatus")
    public Map<String,Object> updateCourseOpenStatus(@RequestParam("ids") String ids,
                                                     @RequestParam("status") int status){
        courseOpenBiz.updateCourseOpenStatus(ids,status);
        return ResultUtil.SUCCESS("免费直播状态修改成功");
    }

    /**
     * 通过ID，查询免费直播数据对象
     * @param id 免费直播ID
     * @param setSubjectData 是否设置专业
     * @param setTeacherData 是否设置讲师
     * @param setCreateUserData 是否设置创建人数据
     * @return CourseOpen
     */
    @RequestMapping("/findCourseOpenById")
    public CourseOpen findCourseOpenById(@RequestParam("id") BigDecimal id,
                                         @RequestParam("setSubjectData") boolean setSubjectData,
                                         @RequestParam("setTeacherData") boolean setTeacherData,
                                         @RequestParam("setCreateUserData") boolean setCreateUserData){
        return courseOpenBiz.findCourseOpenById(id,setSubjectData,setTeacherData,setCreateUserData);
    }

    /**
     * 通过ID串，查询免费直播数据Map
     * @param ids 免费直播ID串
     * @param setSubjectData 是否设置专业
     * @param setTeacherData 是否设置讲师
     * @param setCreateUserData 是否设置创建人数据
     * @return List<CourseOpen>
     */
    @RequestMapping("/findCourseOpenMapByIds")
    public Map<BigDecimal,CourseOpen> findCourseOpenMapByIds(@RequestParam("ids") String ids ,
                                                             @RequestParam("setSubjectData") boolean setSubjectData,
                                                             @RequestParam("setTeacherData") boolean setTeacherData,
                                                             @RequestParam("setCreateUserData") boolean setCreateUserData){
        return courseOpenBiz.findCourseOpenMapByIds(ids,setSubjectData,setTeacherData,setCreateUserData);
    }

    /**
     * 通过ID串，查询免费直播数据列表
     * @param ids 免费直播ID串
     * @param setSubjectData 是否设置专业
     * @param setTeacherData 是否设置讲师
     * @param setCreateUserData 是否设置创建人数据
     * @return List<CourseOpen>
     */
    @RequestMapping("/findCourseOpenListByIds")
    public List<CourseOpen> findCourseOpenListByIds(@RequestParam("ids") String ids ,@RequestParam("setSubjectData") boolean setSubjectData,
                                                    @RequestParam("setTeacherData") boolean setTeacherData,
                                                    @RequestParam("setCreateUserData") boolean setCreateUserData){
        return courseOpenBiz.findCourseOpenListByIds(ids,setSubjectData,setTeacherData,setCreateUserData);
    }

    /**
     * 多条件查询免费直播数据列表
     * @param condition 查询条件对象
     * @param setSubjectData 是否设置专业
     * @param setTeacherData 是否设置讲师
     * @param setCreateUserData 是否设置创建人数据
     * @param setCreateUserData 是否设置直播预约数据
     * @return List<CourseOpen>
     */
    @RequestMapping("/findCourseOpenList")
    public List<CourseOpen> findCourseOpenList(@RequestBody CourseOpenCondition condition,
                                               @RequestParam("setSubjectData") boolean setSubjectData,
                                               @RequestParam("setTeacherData") boolean setTeacherData,
                                               @RequestParam("setCreateUserData") boolean setCreateUserData,
                                               @RequestParam("setReservationData") boolean setReservationData){
        return courseOpenBiz.findCourseOpenList(condition,setSubjectData,setReservationData,setTeacherData,setCreateUserData);
    }

    /**
     * 分页查询免费直播数据列表
     * @param condition 查询条件对象
     * @param currentPage 页码
     * @param pageSize  显示页数
     * @param setSubjectData 是否设置专业
     * @param setTeacherData 是否设置讲师
     * @param setCreateUserData 是否设置创建人数据
     * @param setCreateUserData 是否设置直播预约数据
     * @return PageInfo<CourseOpen>
     */
    @RequestMapping("/findCourseOpenPage")
    public PageInfo<CourseOpen> findCourseOpenPage(@RequestBody CourseOpenCondition condition,
                                                   @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage,
                                                   @RequestParam(value = "pageSize",required = false,defaultValue = "14") Integer pageSize,
                                                   @RequestParam("setSubjectData") boolean setSubjectData,
                                                   @RequestParam("setTeacherData") boolean setTeacherData,
                                                   @RequestParam("setCreateUserData") boolean setCreateUserData,
                                                   @RequestParam("setReservationData") boolean setReservationData){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        return courseOpenBiz.findCourseOpenPage(condition,page,setSubjectData,setReservationData,setTeacherData,setCreateUserData);
    }

    /**
     * 后台管理员开始直播
     * @param id 免费直播ID
     * @param sysUserId 登录用户ID
     * @param auth 认证当前用户与直播讲师一致
     * @return  Map<String,Object>
     */
    @RequestMapping("/startAdminCourseOpenLive")
    public Map<String,Object> startAdminCourseOpenLive(@RequestParam("id") BigDecimal id,
                                                @RequestParam("sysUserId") BigDecimal sysUserId,
                                                @RequestParam(value = "auth",required = false,defaultValue = "false") boolean auth)throws IOException {
        CourseOpen courseOpen = courseOpenBiz.findCourseOpenById(id,false,true,false);
        if(ObjectUtils.isEmpty(courseOpen)){
            return ResultUtil.ERROR("免费直播不存在");
        }
        if(courseOpen.getPlayStatus()==2){
            int preEnterTime = courseOpen.getPreEnterTime();
            long time = courseOpen.getOpenTime().getTime() - System.currentTimeMillis();
            if(time > (preEnterTime * 60 * 1000)){
                return ResultUtil.ERROR("免费直播未开始");
            }
        }
        if(courseOpen.getPlayStatus()==3){
            return ResultUtil.ERROR("免费直播已结束");
        }
        if(ObjectUtils.isEmpty(courseOpen.getTeacher())){
            return ResultUtil.ERROR("免费直播关联讲师不存在");
        }
        List<Map<String,Object>> teacherList = new ArrayList<>();
        teacherList.add(courseOpen.getTeacher());//主讲师
        if(ObjectUtils.isNotEmpty(courseOpen.getTeacherOne())){//助教1
            teacherList.add(courseOpen.getTeacherOne());
        }
        if(ObjectUtils.isNotEmpty(courseOpen.getTeacherTwo())){//助教2
            teacherList.add(courseOpen.getTeacherTwo());
        }
        String playType = courseOpen.getPlayType();
        if (playType.equals("CC")) {
            TreeMap<String, String> configMap = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
            String url = "https://view.csslcloud.net/api/view/lecturer?roomid=" + courseOpen.getLiveUrl() + "&userid=" + configMap.get("ccAppId");
            return ResultUtil.SUCCESS("验证成功", url);
        }
        return ResultUtil.ERROR("直播地址错误");
    }

    /**
     * 获取当前正在直播的免费直播
     * @return
     */
    @RequestMapping("/findNowLiveCourseOpen")
    public CourseOpen findNowLiveCourseOpen(){
        return courseOpenBiz.findNowLiveCourseOpen();
    }

    /**
     * 播放接口
     * @param id 免费直播ID
     * @param userId 用户ID
     * @param form 来源
     * @return Map<String,Object>
     */
    @RequestMapping("/playOpenLive")
    public Map<String,Object> playOpenLive(@RequestParam("id") BigDecimal id,
                                           @RequestParam("userId") BigDecimal userId,
                                           @RequestParam("form") String form)throws IOException{
        Map<String,Object> userMap = cusUserService.userInfo(userId,false,false,false,false,false,false,false);
        if(ObjectUtils.isEmpty(userMap)){
            return ResultUtil.ERROR("请登录后再操作");
        }
        CourseOpen courseOpen = courseOpenBiz.findCourseOpenById(id,false,false,false);
        if(ObjectUtils.isEmpty(courseOpen)){
            return ResultUtil.ERROR("免费直播数据不存在，播放失败");
        }
        if(courseOpen.getPlayStatus()==2){
            long time = courseOpen.getOpenTime().getTime() - System.currentTimeMillis();
            int preEnterTime = courseOpen.getPreEnterTime();
            if(time > (preEnterTime * 60 * 1000)){
                return ResultUtil.ERROR("免费直播未开始");
            }
        }
        String STATUS="LIVE";
        Map<String,Object> resultMap = null;
        TreeMap<String,String> configMap =  null;
        if(courseOpen.getPlayStatus()==3){//如果已结束，看是否有回放
            if(courseOpen.getReplay().intValue()==2){
                if(!courseOpen.getPlayType().equals("96K")){
                    String backCode = courseOpen.getBackCode();
                    if(!StringUtils.isNotEmpty(backCode)){
                        return ResultUtil.ERROR("直播已结束，且未设置回放内容");
                    }
                }
                resultMap = ResultUtil.SUCCESS(courseOpen);
                TreeMap<String, String> configMapTO = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
                if ((courseOpen.getPlayType().equals("TT"))) {
                    configMap = sysConfigService.getSysConfigContext(ConfigName.V96K);
                    String backCode = courseOpen.getBackCode();
                    if (StringUtils.isEmpty(backCode)) {
                        return ResultUtil.ERROR("直播回放还未生成，请稍后重试");
                    }
                    resultMap.put("playerUrl", configMap.get("player"));
                    resultMap.put("playStatus", "STATUS_CODE");
                    STATUS = "REPLAY";
                    resultMap.put("status", STATUS);
                    if (configMapTO.get("isK96keVideo").equals("ON")) {
                        resultMap.put("isK96keVideo", "TRUE");
                    }
                    return resultMap;
                } else if (courseOpen.getPlayBackType().equals(MaterialType.TYPE_KEY_LIVE.getKey())&&courseOpen.getPlayType().equals("CC")){
                    String backCode = courseOpen.getBackCode();
                    if(StringUtils.isEmpty(backCode)){
                        return ResultUtil.ERROR("直播回放还未生成，请稍后重试");
                    }
                    resultMap.put("playerUrl",backCode+"&autoLogin=true&viewertoken="+courseOpen.getStudentCode()+"&viewername="+userMap.get("nickname"));
                    resultMap.put("playStatus","STATUS_URL");
                    resultMap.put("status","REPLAY");
                    return resultMap;
                }
            }else{
                return ResultUtil.ERROR("直播已结束，且没有设置回放");
            }
        }
        resultMap = ResultUtil.SUCCESS(courseOpen);
        resultMap.put("status",STATUS);
        if(form.equals(CourseOpenForm.APP)){
            return resultMap;
        }
        courseOpen.setTLiveParams(this.getLiveParamMap(courseOpen, userMap));
        resultMap.put("playerUrl",this.getLiveUrl(courseOpen,userMap,form));
        //参加直播赠送优惠券
        opCouponCodeService.giveUserCourseOpenCode(userId,courseOpen.getId());
        //修改实际参加人数
        courseOpenBiz.updateCourseOpenAttendNum(courseOpen.getId(),courseOpen.getAttendNum());
        return resultMap;
    }

    /**
     * 获取主播放的链接
     * @param id 课程ID
     * @return 直播链接
     */
    @RequestMapping("/getAdminCopyLiveUrl")
    public String getAdminCopyLiveUrl(@RequestParam("id") BigDecimal id){
        CourseOpen courseOpen = courseOpenBiz.findCourseOpenById(id,false,false,false);
        if(courseOpen.getPlayType().equals("CC")){
            TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
            String url ="https://view.csslcloud.net/api/view/lecturer?roomid="+courseOpen.getLiveUrl()+"&userid="+configMap.get("ccAppId");
            courseOpen.setPlayUrl(url);
        }else if(courseOpen.getPlayType().equals("POLYV")){
            courseOpen.setPlayUrl("https://live.polyv.net/start-client.html?channelId="+courseOpen.getLiveUrl());
        }
        return courseOpen.getPlayUrl();
    }

    /**
     * 复制直播链接
     * @param id 课程ID
     * @return 链接
     */
    @RequestMapping("/getCopyLiveUrl")
    public String getCopyLiveUrl(@RequestParam("id") BigDecimal id){
        CourseOpen courseOpen = courseOpenBiz.findById(id);
        return getLiveUrl(courseOpen,null,"");
    }

    /**
     * 获取app免费直播参数
     * @param courseOpen
     * @param userMap
     * @return
     */
    private Map getLiveParamMap(CourseOpen courseOpen, Map<String, Object> userMap) {
        Map resultMap = new HashMap();
        try {
            Map params = new HashMap();
            params.put("classId", courseOpen.getRoomId());
            params.put("role", "3");
            params.put("uuid", userMap.get("id").toString());
            params.put("nickName", userMap.get("nickname"));
            params.put("avatar", userMap.get("avatar"));
            Map<String, Object> liveParamMap = ttServiceUtils.getLiveParam(params);
            if ((boolean) liveParamMap.get("success")) {
                Map entityMap = (Map) liveParamMap.get("entity");
                resultMap.put("roomId", entityMap.get("classId"));
                resultMap.put("userId", entityMap.get("UID"));
                resultMap.put("safeKey", entityMap.get("safeKey"));
                resultMap.put("timeStamp", entityMap.get("timeStamp"));
                resultMap.put("expires", entityMap.get("expires_in"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 获取直播URL
     * @param courseOpen
     * @param userMap
     * @param form
     * @return
     */
    private String getLiveUrl(CourseOpen courseOpen,Map<String,Object> userMap,String form){
        TreeMap<String,String> configMap;
        try{
            if (courseOpen.getPlayType().equals("TT")) {
                Map params = new HashMap();
                params.put("classId", courseOpen.getRoomId());
                params.put("role", "3");
                params.put("uuid", userMap.get("id").toString());
                params.put("nickName", userMap.get("nickname"));
                params.put("avatar", userMap == null ? "" : userMap.get("avatar"));
                Map<String, Object> LiveParamMap = ttServiceUtils.getLiveParam(params);
                if ((boolean) LiveParamMap.get("success")) {
                    Map entityMap = (Map) LiveParamMap.get("entity");
                    if (LoginForm.LOGIN_FROM_MOBILE.equals(form)) {
                        return entityMap.get("mRoomUrl").toString();
                    } else if (LoginForm.LOGIN_FROM_PC.equals(form)) {
                        return entityMap.get("classRoomUrl").toString();
                    }
                }
            } else if (courseOpen.getPlayType().equals("CC")) {
                configMap = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
                if(userMap !=null){//学生
                    return "https://view.csslcloud.net/api/view/index?roomid="+courseOpen.getLiveUrl()+"&userid="+configMap.get("ccAppId")+"&autoLogin=true&viewername="+ URLDecoder.decode(userMap.getOrDefault("nickname","").toString(),"utf-8")+"&viewertoken="+courseOpen.getStudentCode();
                }else{//后台
                    return "https://view.csslcloud.net/api/view/index?roomid="+courseOpen.getLiveUrl()+"&userid="+configMap.get("ccAppId")+"&autoLogin=true&viewertoken="+courseOpen.getStudentCode();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询免费直播总数量数据
     * @return CourseOpenSumCount
     */
    @RequestMapping("/queryCourseOpenSumCount")
    public CourseOpenSumCount queryCourseOpenSumCount(){
        return courseOpenBiz.queryCourseOpenSumCount();
    }

    /**
     * 查询免费直播
     * @param whereSql
     * @return
     */
    @RequestMapping("findCourseOpenBySql")
    public CourseOpen findCourseOpenBySql(@RequestParam("whereSql") String whereSql){
        CourseOpen courseOpen = courseOpenBiz.findOne(whereSql,null);
        return courseOpen;
    }
}
